from django.shortcuts import render
from .forms import LeaveRequestForm
from .models import LeaveRequest

def leave_request(request):
    if request.method == 'POST':
        form = LeaveRequestForm(request.POST)
        if form.is_valid():
            # 获取表单数据并做必要的转换
            data = {
                'student_name': form.cleaned_data['student_name'],
                'teacher_name': form.cleaned_data['teacher_name'],
                'student_id': form.cleaned_data['student_id'],
                'level': form.cleaned_data['level'],
                'level_2': form.cleaned_data['level_2'],
                'major': form.cleaned_data['major'],
                'if_or_school': form.cleaned_data['if_or_school'],
                'if_or_city': form.cleaned_data['if_or_city'],
                'leave_request_type': form.cleaned_data['leave_request_type'],
                'phone_num': form.cleaned_data['phone_num'],
                'start_time': form.cleaned_data['start_time'],
                'end_time': form.cleaned_data['end_time'],
                'txt_': form.cleaned_data['txt_'],
                'txt_2': form.cleaned_data['txt_2'],
                'time_1': form.cleaned_data['time_1'],
                'time_2': form.cleaned_data['time_2'],

            }

            leave_request_instance = LeaveRequest(
                student_name=form.cleaned_data['student_name'],
                teacher_name=form.cleaned_data['teacher_name'],
                student_id=form.cleaned_data['student_id'],
                level=form.cleaned_data['level'],
                level_2=form.cleaned_data['level_2'],
                major=form.cleaned_data['major'],
                # 将 "是" 转换为 1，将 "否" 转换为 0
                if_or_school=1 if form.cleaned_data['if_or_school'] == '是' else 0,
                if_or_city=1 if form.cleaned_data['if_or_city'] == '是' else 0,
                leave_request_type=form.cleaned_data['leave_request_type'],
                phone_num=form.cleaned_data['phone_num'],
                start_time=form.cleaned_data['start_time'],
                end_time=form.cleaned_data['end_time'],
                text_1=form.cleaned_data['txt_'],  # 匹配新字段 text_1
                text_2=form.cleaned_data['txt_2'],  # 匹配新字段 text_2
                time_1=form.cleaned_data['time_1'],
                time_2=form.cleaned_data['time_2'],
            )
            leave_request_instance.save()

            # 渲染感谢页面，并传递表单数据
            return render(request, 'leave_requests/request_ans.html', data)
    else:
        form = LeaveRequestForm()

    return render(request, 'leave_requests/leave_request_form.html', {'form': form})
